
function Promise(excuter){
  
    this.PromiseState='pending'
    this.PromiseResult=null
    let that=this
  
    this.callbacks=[]

     function  reslove(data){
        that.PromiseState='fulfilled'
        that.PromiseResult=data
        that.callbacks.forEach(element => {
            element.onRslove(data)
        });

     }

     function  reject(data){
        that.PromiseState='rejected'
        that.PromiseResult=data
        that.callbacks.forEach(element => {
            element.onReject(data)
            
        });
     }


    try {
        excuter(reslove,reject)
    } catch (error) {
        reject(error)
    }

}

Promise.prototype.then=function (onRslove,onReject) { 
   
    let that=this
    return new Promise((reslove,reject)=>{
            if( that.PromiseState=='fulfilled' ){
               
                let result=onRslove(that.PromiseResult)
                if(result instanceof Promise){
                    result.then((v)=>{
                        reslove(v)
                    },(error)=>{
                        reject(error)
                    })
                }else{
                   // console.log('成功成功成功成功成功'+result)
                    reslove(result)
                }


            }

            if( that.PromiseState=='rejected' ){
                //console.log('失败失败失败失败失败失败失败失败')
                let result=onReject(that.PromiseResult)
                if(result instanceof Promise){
                    result.then((v)=>{
                        reslove(v)
                    },(error)=>{
                        reject(error)
                    })
                }else{
                    reslove(result)
                }
            }


            if( that.PromiseState=='pending' ){
                that.callbacks.push({
                    onRslove,
                    onReject,
                })
            }

    })


 }


 Promise.all=function(promsieData){
       
        console.log(promsieData)
        let aa=0,dataArr=[]
        let bb=''
        return new Promise((resolve, reject)=>{
            for(let ii=0;ii<promsieData.length;ii++){
                promsieData[ii].then((vv)=>{
                    aa++
                    dataArr[ii]=vv
                },(err)=>{
                    bb=err
                })
            }
            if(aa==promsieData.length){
                resolve(dataArr)
            }else{
                reject(bb)
            }
        })
      

 }

 
 Promise.race=function(promsieData){
       
    return new Promise((resolve, reject)=>{
        for(let ii=0;ii<promsieData.length;ii++){
            promsieData[ii].then((vv)=>{
                resolve(vv)
            },(err)=>{
                reject(err)
            })
        }
        
    })
  

}